var switchdata = {}, firewalldata = {}, flags = true, {Line, Liquid, Gauge, Column} = G2Plot;
;
// 基于准备好的dom，初始化echarts实例
var geoMapChart = echarts.init(document.getElementById('deviceMap'));
var myPieChart = echarts.init(document.getElementById('d3Pie'));
var applyWebChart = echarts.init(document.getElementById('applyWeb'));
var applyDatabaseChart = echarts.init(document.getElementById('applyDatabase'));
var unnormalDeviceChart = echarts.init(document.getElementById('unnormalDevice'));
var createImg = document.createElement("img");
createImg.src = contextPath + '/page/adminSystem/index/bigScreen/navigation/two/img/city_bg.png';

/**
 *   "000000004ff3ad18014ff41e9c2300b1": "专用数通设备",
 *     "000000004ff3ad18014ff41e9c2300b2": "通用数通设备",
 *     "000000004ff3ad18014ff418a73800a7": "专用计算机",
 *     "000000004ff3ad18014ff423c9fe00b9": "专用网络安全设备",
 *     "0188e36f66dd11eba69800ffaabbcc01": "WEB应用",
 *     "0188e36f66dd11eba69800ffaabbcc02": "数据库",
 *     "0188e36f66dd11eba69800ffaabbccdd": "其他设备",
 *     "4028f6db55c9acd30155c9b53fae0004": "专用服务器",
 *     "ff808081525e04e10152e80e78670149": "专用工作站",
 */

const STATUS_MAP = {
    "0": "在线",
    "1": "离线",
    "2": "告警",
    "3": "未监控"
}

const ASSET_TYPE_SET = [
    "服务器",
    "数通设备",
    "网络安全设备",
    "其他"
]
/**
 * 设备列表的类型
 */
const ASSET_TYPE_MAP = {
    "服务器": ['4028f6db55c9acd30155c9b53fae0004'],
    "数通设备": ['000000004ff3ad18014ff41e9c2300b1', '000000004ff3ad18014ff41e9c2300b2'],
    "网络安全设备": ['000000004ff3ad18014ff423c9fe00b9'],
    "其他": ['0188e36f66dd11eba69800ffaabbccdd', 'ff808081525e04e10152e80e78670149', '000000004ff3ad18014ff418a73800a7'],
}
var COUNT_MAP = {
    "服务器": 0,
    "数通设备": 0,
    "网络安全设备": 0,
    "其他": 0,
}


var URL = {
    "getNetworkGeoMap": contextPath + "/assetNetworkScreen/getNetworkGeoMap?code=",
    "getNetworkSummary": contextPath + "/assetNetworkScreen/getNetworkSummary?code=",
    "getNetworkTypeSummary": contextPath + "/assetNetworkScreen/getNetworkTypeSummary?code=",
    "getCodeName": contextPath + "/assetNetworkScreen/getCodeName?code=",
    "getProvOrgSummary": contextPath + "/assetNetworkScreen/getProvOrgSummary?code=",
    "getCityOrgSummary": contextPath + "/assetNetworkScreen/getCityOrgSummary?code=",
    "getCitys": contextPath + "/assetNetworkScreen/getCitys?code=",
    "getRecent7DaysAlarmSummary": contextPath + "/assetNetworkScreen/getRecent7DaysAlarmSummary?code=",
    "getRecent7DaysAlarm": contextPath + "/assetNetworkScreen/getRecent7DaysAlarm?code=",
    "getTypesCount": contextPath + "/assetNetworkScreen/getTypesCount?code=",
    "getAppSummary": contextPath + "/assetNetworkScreen/getAppSummary?code=",
    "reStat": contextPath + "/assetNetworkScreen/reStat?code=",
    "getWebSummary": contextPath + "/assetNetworkScreen/getWebSummary?code=",
    "getAlarmweight": contextPath + "/assetNetworkScreen/getAlarmweight?isFirst=false",
}

var globalDc = null;

/**
 * 渲染机房信息
 * @param globalDc
 */
function renderDcInfo(globalDc) {

}

/**
 * 查询所有机房
 */
function getAllDc() {
    COUNT_MAP = new Map()
    COUNT_MAP.set('服务器', 0);
    COUNT_MAP.set('数通设备', 0);
    COUNT_MAP.set('网络安全设备', 0);
    COUNT_MAP.set('其他', 0);

    statusMap = new Map()

    $.ajax({
        url: top.contextPath + "/dc/datacenter/listDataCenter",
        method: 'POST',
        success: function (data) {
            if (data && data.code === '0') {
                let list = data.data;
                if (list != null && list.length > 0) {
                    globalDc = list[0];
                } else {
                    globalDc = null;
                }
                if (globalDc) {
                    // 开始渲染数据
                    renderDcInfo(globalDc);
                    console.log(globalDc);
                    getRackAssetListByDcId(globalDc.id)
                }


            }
        }
    });
}

/**
 * 获取机房信息
 * @param id
 */
function getRackAssetListByDcId(id) {
    let prams = {
        "kw": "",
        "dcId": id
    }
    $.ajax({
        url: top.contextPath + "/dc/rack/getRackAssetListByDcId",
        type: 'POST',
        contentType: 'application/json;charset=utf-8',
        dataType: 'json',
        data: JSON.stringify(prams),
        success: function (data) {
            if (data && data.code === '0') {
                let list = data.data;
                // 1.统计数据 资产类型分布 资产状态分布 各个机柜的状态分布
                for (const ele of list) {
                    // 机柜里存放的资产信息
                    let assets = ele.assets;
                    // 遍历assets
                    let rackStatusMap = new Map()
                    if (null != assets && assets.length > 0) {

                        for (const ele of assets) {
                            let assetType = ele['assetType'];

                            if (ASSET_TYPE_MAP['数通设备'].includes(assetType)) {
                                // 路由器 防火墙 交换机
                                COUNT_MAP.set('数通设备', COUNT_MAP.get('数通设备') + 1)
                            } else if (ASSET_TYPE_MAP['服务器'].includes(assetType)) {
                                // 服务器 工作站
                                COUNT_MAP.set('服务器', COUNT_MAP.get('服务器') + 1)
                            } else if (ASSET_TYPE_MAP['网络安全设备'].includes(assetType)) {
                                // 网络设备
                                COUNT_MAP.set('网络安全设备', COUNT_MAP.get('网络安全设备') + 1)
                            } else {
                                // 其他
                                COUNT_MAP.set('其他', COUNT_MAP.get('其他') + 1)
                            }
                            let status = ele['availability'];
                            statusMap.set(status, statusMap.get(status) == null ? 1 : statusMap.get(status) + 1)
                            rackStatusMap.set(status, rackStatusMap.get(status) == null ? 1 : rackStatusMap.get(status) + 1)

                        }
                    }
                    console.log(rackStatusMap)
                }
                console.log(COUNT_MAP)
                console.log(statusMap)
            }
        }
    });
}

function init(paramCode) {
    try {
        initMap(paramCode);
    } catch (e) {
    }
    try { //cpu折线图
        deviceCPU(paramCode);
    } catch (e) {
    }

    try {
        initAlarmList(paramCode);
    } catch (e) {
    }

    $.ajax({
        url: URL.getAppSummary + paramCode,
        method: 'POST',
        dataType: 'json',
        async: true, // 设置为异步请求
        success: function (data) {
            if (data) {
                if (data['Database']) {
                    //数据库连通占比
                    let mysql = [
                        {name: '数据库连通占比', value: data['Database'][1], max: data['Database'][0]},
                    ];
                    let formatStr = `${data['Database'][1]}/${data['Database'][0]}`;
                    applyDatabase(mysql, formatStr);
                } else {
                    let mysql = [
                        {name: '数据库连通占比', value: 0, max: 1},
                    ];
                    let formatStr = `0/0`;
                    applyDatabase(mysql, formatStr);
                }
                if (data['Web']) {
                    //WEB应用连通占比
                    let web = [
                        {name: 'WEB应用连通占比', value: data['Web'][1], max: data['Web'][0]},
                    ];
                    let formatStr = `${data['Web'][1]}/${data['Web'][0]}`;
                    applyWeb(web, formatStr);
                } else {
                    let web = [
                        {name: 'WEB应用连通占比', value: 0, max: 1},
                    ];
                    let formatStr = `0/0`;
                    applyWeb(web, formatStr);
                }
            }
        }
    });

    try { //网络及安全设备监控
        unnormalDevice(paramCode);
    } catch (e) {
    }
    try { //7天告警概况
        barshow(paramCode);
    } catch (e) {
    }

    try {
        //d3Pie
        thireeDPie(paramCode);
    } catch (e) {

    }

}


/**
 * 渲染告警信息
 * @param params
 */
function initAlarmList(params) {

    $.ajax({
        url: URL.getAlarmweight,
        method: 'POST',
        dataType: 'json',
        success: function (data) {
            if (data && data.length) {
                let str = '';
                const first10Items = data.slice(0, 10);

                for (const item of first10Items) {
                    let assetType = item.assetType ? item.assetType.split('/')[0] : "";
                    if (item.weight === 3) {
                        // 红色
                        str += `<div style="display:flex;text-align: left;color:#FF2900;line-height: 22px;font-size: 12px">
                    <div style="width:32%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${item.desc}">${item.desc}</div>
                    <div style="width:24%">${item.relatedIps}</div>
                    <div style="width:14%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${assetType}">${assetType}</div>
                    <div style="width:32%">${item.lastTime}</div>
                </div>`;
                    } else if (item.weight === 2) {
                        // 黄色
                        str += `<div style="display:flex;text-align: left;color:#FFB300;line-height: 22px;font-size: 12px">
                    <div style="width:32%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${item.desc}">${item.desc}</div>
                    <div style="width: 24%">${item.relatedIps}</div>
                    <div style="width:14%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${assetType}">${assetType}</div>
                    <div style="width:32%">${item.lastTime}</div>
                </div>`;
                    } else {
                        str += `<div style="display:flex;text-align: left;color:#03A1D6;line-height: 22px;font-size: 12px">
                    <div style="width:32%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${item.desc}">${item.desc}</div>
                    <div style="width: 24%">${item.relatedIps}</div>
                    <div style="width:14%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${assetType}">${assetType}</div>
                    <div style="width:32%">${item.lastTime}</div>
                </div>`;
                    }
                }
                $('.alarmList').html(str);
            } else {
                $(".alarmList").html('<div style="text-align: center; padding-top: 10px; font-size: 15px;">暂无告警内容！</div>');
            }
        }
    });
}


function deviceCPU(paramCode) {
    $.ajax({
        url: URL.reStat + paramCode,
        method: 'POST',
        dataType: 'json',
        async: true, // 设置为异步请求
        success: function (data) {
            let todayData = data.todayData;

            $(".fuwuqi-rate").html(todayData['cpuUsage'] + '%');
            $(".cunchu-rate").html(todayData['diskUsage'] + '%');
            $(".neicun-rate").html(todayData['memoryUsage'] + '%');
            let trendData = data.trendData;
            let date = trendData.date;
            let cpuUsage = trendData.cpuUsage;
            let diskUsage = trendData.diskUsage;
            let memoryUsage = trendData.memoryUsage;
            let datas = []
            for (let i = 0; i < date.length; i++) {
                const trendDatum = date[i];
                datas.push({
                    "name": "CPU利用率",
                    "year": trendDatum,
                    "gdp": cpuUsage[i]
                })
            }
            for (let i = 0; i < date.length; i++) {
                const trendDatum = date[i];
                datas.push({
                    "name": "内存使用率",
                    "year": trendDatum,
                    "gdp": memoryUsage[i]
                })
            }
            for (let i = 0; i < date.length; i++) {
                const trendDatum = date[i];
                datas.push({
                    "name": "存储使用率",
                    "year": trendDatum,
                    "gdp": diskUsage[i]
                })
            }

            document.getElementById('deviceCPU').innerHTML = '';
            new Line('deviceCPU', {
                data: datas,
                xField: 'year',
                yField: 'gdp',
                seriesField: 'name',
                yAxis: {
                    label: {
                        style: {
                            fill: '#fff',
                        }
                        //  formatter: (v) => `${(v / 10e8).toFixed(1)} B`,
                    },
                },
                label: {
                    style: {
                        fill: '#fff',
                    }
                },
                xAxis: {
                    label: {
                        style: {
                            fill: '#fff',
                        }
                    }
                },
                isGroup: 'true',
                legend: {
                    position: 'top',
                    flipPage: true,
                    marker: {
                        symbol: 'square'
                    },
                    itemName: {
                        style: {
                            fill: '#fff'
                        }
                    },
                },
                smooth: true,
                // 配置折线趋势填充
                color: ['#00A6F3', '#0DCEBE', '#ADAED9'],
                area: {
                    style: {
                        fillOpacity: 0.15,
                    },
                },
                animation: {
                    appear: {
                        animation: 'wave-in',
                        duration: 3000,
                    },
                },

            }).render();
        }
    });


}

function applyWeb(dataList, formatStr) {
    // 头部数据
    let topData = dataList.map((item) => {
        return {name: '', value: item.max, symbolPosition: 'end'};
    });
    // 底部立体柱子
    let bottomBar = dataList.map((item) => {
        return {
            value: item.value
        };
    });
    // 底下圆片
    let bottomCircle = dataList.map((item) => {
        return {name: '', value: item.max};
    });
    // 中间圆片
    let middleCircle = dataList.map((item) => {
        return {name: '', value: item.value, symbolPosition: 'end'};
    });
    // 上边的柱子
    let upBar = dataList.map((item) => {
        return {name: item.name, value: item.max - item.value};
    });

    let option = {
        grid: {
            bottom: '8%',
            top: '7%',
            right: '0%',
            left: '0%'
        },
        xAxis: {
            data: ['WEB应用连通占比'],
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            axisLabel: {
                show: true,
                textStyle: {
                    color: '#fff'
                },
                margin: 30 //刻度标签与轴线之间的距离。
            }
        },
        yAxis: {
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            axisLabel: {
                show: false
            }
        },
        series: [
            // 头
            {
                name: '',
                type: 'pictorialBar',
                symbolSize: [90, 20],
                symbolOffset: [0, -10],
                z: 12,
                itemStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(
                            1,
                            0,
                            1,
                            1,
                            [
                                {
                                    offset: 0,
                                    color: '#188B98',
                                    opacity: 0.4
                                },
                                {
                                    offset: 1,
                                    color: '#16C7C7',
                                    opacity: 0.4
                                }
                            ],
                            false
                        )
                    }
                },
                data: topData,
                cursor: 'default',
            },
            //底部立体柱
            {
                cursor: 'default',
                stack: '1',
                type: 'bar',
                silent: true,
                barWidth: 90,
                data: bottomBar,
                itemStyle: {
                    normal: {
                        color: {
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            type: 'linear',
                            global: false,
                            colorStops: [
                                {
                                    //第一节下面
                                    offset: 0,
                                    color: '#109E9F'
                                },
                                {
                                    offset: 1,
                                    color: '#4FE6E8',
                                    // color: '#FDCB58',
                                }
                            ]
                        }
                    }
                }
            },
            //最底下的圆片
            {
                cursor: 'default',
                name: '',
                type: 'pictorialBar',
                symbolSize: [90, 20],
                symbolOffset: [0, 10],
                z: 12,
                itemStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(
                            1,
                            0,
                            1,
                            1,
                            [
                                {
                                    offset: 0,
                                    color: '#188B98',
                                    opacity: 0.4
                                },
                                {
                                    offset: 1,
                                    color: '#16C7C7',
                                    opacity: 0.4
                                }
                            ],
                            false
                        )
                    }
                },
                data: bottomCircle
            },
            // 中间圆片
            {
                cursor: 'default',
                name: '',
                type: 'pictorialBar',
                symbolSize: [90, 20],
                symbolOffset: [0, -10],
                itemStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(
                            0,
                            0,
                            0,
                            1,
                            [
                                {
                                    offset: 0,
                                    color: '#03B1C3'
                                },
                                {
                                    offset: 1,
                                    color: '#5CF6F8'
                                }
                            ],
                            false
                        )
                    }
                },
                z: 12,
                data: middleCircle
            },
            //上部立体柱
            {
                //上部立体柱
                cursor: 'default',
                stack: '1',
                type: 'bar',
                itemStyle: {
                    normal: {
                        color: '#27676B',
                        opacity: 0.7
                    }
                },
                label: {
                    show: true,
                    position: 'inside', //top / left / right / bottom / inside / insideLeft / insideRight / insideTop / insideBottom / insideTopLeft / insideBottomLeft / insideTopRight / insideBottomRight
                    distance: 20,
                    color: '#fff',
                    fontSize: 30,
                    fontFamily: 'DINCond-Medium-Regular',
                    formatter: function (item) {
                        return formatStr;
                    }
                },
                silent: true,
                barWidth: 90,
                //barGap: '-100%', // Make series be overlap
                data: upBar
            }
        ]
    };
    applyWebChart.setOption(option);
}

function applyDatabase(dataList, formatStr) {

    // 头部数据
    let topData = dataList.map((item) => {
        return {name: '', value: item.max, symbolPosition: 'end'};
    });
    // 底部立体柱子
    let bottomBar = dataList.map((item) => {
        return {
            value: item.value
        };
    });
    // 底下圆片
    let bottomCircle = dataList.map((item) => {
        return {name: '', value: item.max};
    });
    // 中间圆片
    let middleCircle = dataList.map((item) => {
        return {name: '', value: item.value, symbolPosition: 'end'};
    });
    // 上边的柱子
    let upBar = dataList.map((item) => {
        return {name: item.name, value: item.max - item.value};
    });

    let option = {
        grid: {
            bottom: '8%',
            top: '7%',
            right: '0%',
            left: '0%'
        },
        xAxis: {
            data: ['数据库连通占比'],
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            axisLabel: {
                show: true,
                textStyle: {
                    color: '#fff'
                },
                margin: 30 //刻度标签与轴线之间的距离。
            }
        },
        yAxis: {
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            axisLabel: {
                show: false
            }
        },
        series: [
            // 头
            {
                cursor: 'default',
                name: '',
                type: 'pictorialBar',
                symbolSize: [90, 20],
                symbolOffset: [0, -10],
                z: 12,
                itemStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(
                            1,
                            0,
                            1,
                            1,
                            [
                                {
                                    offset: 0,
                                    color: '#0248B6'
                                },
                                {
                                    offset: 1,
                                    color: '#033B93'
                                }
                            ],
                            false
                        )
                    }
                },
                data: topData
            },
            //底部立体柱
            {
                cursor: 'default',
                stack: '1',
                type: 'bar',
                silent: true,
                barWidth: 90,
                data: bottomBar,
                itemStyle: {
                    normal: {
                        color: {
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            type: 'linear',
                            global: false,
                            colorStops: [
                                {
                                    //第一节下面
                                    offset: 0,
                                    color: '#025BD3'
                                },
                                {
                                    offset: 1,
                                    color: '#43bafe'
                                }
                            ]
                        }
                    }
                }
            },
            //最底下的圆片
            {
                cursor: 'default',
                name: '',
                type: 'pictorialBar',
                symbolSize: [90, 20],
                symbolOffset: [0, 10],
                z: 12,
                itemStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: '#025BD3'
                            },
                            {
                                offset: 1,
                                color: '#025BD3'
                            }
                        ])
                    }
                },
                data: bottomCircle
            },
            // 中间圆片
            {
                cursor: 'default',
                name: '',
                type: 'pictorialBar',
                symbolSize: [90, 20],
                symbolOffset: [0, -10],
                itemStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(
                            1,
                            0,
                            1,
                            1,
                            [
                                {
                                    offset: 0,
                                    color: '#0CB7FA'
                                },
                                {
                                    offset: 1,
                                    color: '#0CB3F8'
                                }
                            ],
                            false
                        )
                    }
                },
                z: 12,
                data: middleCircle
            },
            //上部立体柱
            {
                cursor: 'default',
                //上部立体柱
                stack: '1',
                type: 'bar',
                itemStyle: {
                    normal: {
                        color: '#062D6C',
                        opacity: 0.7
                    }
                },
                label: {
                    show: true,
                    position: 'inside', //top / left / right / bottom / inside / insideLeft / insideRight / insideTop / insideBottom / insideTopLeft / insideBottomLeft / insideTopRight / insideBottomRight
                    distance: 20,
                    color: '#fff',
                    fontSize: 30,
                    fontFamily: 'DINCond-Medium-Regular',
                    formatter: function (item) {
                        return formatStr;
                    }
                },
                silent: true,
                barWidth: 90,
                //barGap: '-100%', // Make series be overlap
                data: upBar
            }
        ]
    };
    applyDatabaseChart.setOption(option);
}

function unnormalDevice(params) {
    $.ajax({
        url: URL.getWebSummary + params,
        method: 'POST',
        dataType: 'json',
        async: true, // 设置为异步请求
        success: function (data) {
            let totalCount = data.totalCount;
            $(".deviceTotal").html(totalCount);
            $(".abnormalTotal").html(totalCount - data.onlineCount);
            let abnormalRate = 100 - data.onlineRate;
            if (totalCount === 0) {
                abnormalRate = 0;
            }

            let option = {
                tooltip: {
                    // formatter: "{a} <br/>{b} : {c}%"
                },
                series: [
                    {
                        name: '',
                        type: 'gauge',
                        // center: ["50%", "45%"], // 仪表位置
                        radius: "90%", //仪表大小
                        startAngle: 200, //开始角度
                        endAngle: -20, //结束角度
                        axisLine: {
                            lineStyle: { // 属性lineStyle控制线条样式
                                color: [
                                    [0.4, new echarts.graphic.LinearGradient(0, 1, 1, 0, [{
                                        offset: 0.4,
                                        color: "#095B9D" // 50% 处的颜色
                                    }, {
                                        offset: 0.75,
                                        color: "#095B9D" // 40% 处的颜色
                                    }], false)], // 100% 处的颜色

                                    [1, new echarts.graphic.LinearGradient(0, 0, 1, 1, [{
                                        offset: 0.1,
                                        color: "#095B9D" // 50% 处的颜色
                                    }, {
                                        offset: 0.6,
                                        color: "#095B9D" // 40% 处的颜色
                                    }], false)]
                                ],
                                width: 2
                            }
                        },
                        splitLine: {
                            show: false
                        },
                        axisTick: {
                            show: false
                        },
                        axisLabel: {
                            show: false
                        },
                        pointer: {
                            // show: false
                            length: '45%'
                        },
                        detail: {
                            show: false
                        }
                    },
                    {
                        name: '网络及安全设备监控',
                        type: 'gauge',
                        // center: ["50%", "45%"], // 默认全局居中
                        radius: "80%",
                        startAngle: 200,
                        endAngle: -20,
                        axisLine: {
                            show: true,
                            lineStyle: { // 属性lineStyle控制线条样式
                                color: [
                                    [0.5, new echarts.graphic.LinearGradient(0, 1, 1, 0, [{
                                        offset: 0.4,
                                        color: "#5FC24F" // 50% 处的颜色
                                    }, {
                                        offset: 0.75,
                                        color: "#D9B604" // 40% 处的颜色
                                    }], false)], // 100% 处的颜色

                                    [1, new echarts.graphic.LinearGradient(0, 0, 1, 1, [{
                                        offset: 0.1,
                                        color: "#D9B604" // 50% 处的颜色
                                    }, {
                                        offset: 0.6,
                                        color: "#C8242D" // 40% 处的颜色
                                    }], false)]
                                ],
                                width: 10//表盘宽度
                            }
                        },
                        splitLine: { //分割线样式（及10、20等长线样式）
                            show: false
                        },
                        axisTick: { //刻度线样式（及短线样式）
                            show: false
                        },
                        axisLabel: { //文字样式（及“10”、“20”等文字样式）
                            show: false
                        },
                        pointer: {
                            // show: false,
                            length: '55%',
                            width: 10
                        },
                        markPoint: {
                            symbol: 'circle',
                            symbolSize: 7,
                            data: [
                                {x: 'center', y: 'center', itemStyle: {color: '#09194A'}}
                            ]
                        },
                        itemStyle: {
                            color: '#00A0E9'
                        },
                        detail: {
                            formatter: "{score|{value}%}",
                            offsetCenter: [0, '70%'],
                            rich: {
                                score: {
                                    color: "#fff",
                                    fontFamily: 'DINCond-Medium-Regular',
                                    fontSize: 30
                                }
                            }
                        },
                        title: {
                            show: false,
                            color: "#fff",
                            fontFamily: "微软雅黑",
                            fontSize: 16,
                            offsetCenter: [0, "100%"],
                        },
                        data: [{
                            name: '异常设备',
                            value: abnormalRate
                        }]
                    }
                ]
            };
            unnormalDeviceChart.setOption(option);
        }
    });


}


var TypeMap = {
    "asset-DataCommunication": "网络设备",
    "asset-Host": "专用计算机",
    "asset-SafeDevice": "安全设备",
    "asset-Server": "服务器",
    "asset-Software": "应用",
    "asset-Workstation": "专用工作站",
    "asset-other": "其他"
}

function setLabel(params) {
    let optionData = [
        {
            name: '服务器',
            value: 0,
            type: "asset-Server",

        }, {
            name: '网络设备',
            value: 0,
            type: "asset-DataCommunication"
        }, {
            name: '安全设备',
            value: 0,
            type: "asset-SafeDevice"
        }, {
            name: '其他',
            value: 0,
            type: "asset-other"
        }
    ];
    let color = ['#2F57A2', '#5BA3B8', '#E59860', '#AFD8F2'];
    $.ajax({
        url: URL.getTypesCount + params,
        method: 'POST',
        dataType: 'json',
        async: false, // 设置为异步请求
        success: function (data) {
            for (const ele of optionData) {
                ele.value = data[ele.type]
            }
        }
    });

    let filteredData = optionData.filter(item => item.value !== 0);

    return filteredData.map((item, index) => {

        item.itemStyle = {
            color: color[index]
        }
        item.label = {
            normal: {
                show: true,
                color: color[index],
                formatter: [
                    '{b|{b}}',
                    // '{c|{c}}{e|台}',
                    '{d|{d}%}'
                ].join('\n'), // 用\n来换行
                rich: {
                    b: {
                        color: '#41A5FB',
                        fontWeight: 600,
                        lineHeight: 25,
                        fontSize: '16px',
                        align: 'left'
                    },
                    e: {
                        color: '#fff',
                    },
                    c: {
                        fontSize: 22,
                        color: '#fff',
                        textShadowColor: '#1c90a6',
                        textShadowOffsetX: 0,
                        textShadowOffsetY: 2,
                        textShadowBlur: 5
                    },
                    d: {
                        color: '#fff',
                        align: 'left',
                        fontFamily: 'DINCond-Medium-Regular',
                        fontSize: '16px',
                    }
                }
            }
        }
        item.labelLine = {
            normal: {
                lineStyle: {
                    width: 1,
                    color: 'rgba(255,255,255,0.7)'
                }
            }
        }
        return item
    })
}

function thireeDPie(paramCode) {
    // this.statusChart = this.$echarts.init(this.$refs.chart);

    // 传入数据生成 option, 构建3d饼状图, 参数工具文件已经备注的很详细
    let pieData = setLabel(paramCode);
    let option = getPie3D(pieData, 0.8, 240, 28, 26, 1)
    myPieChart.setOption(option);
    // 是否需要label指引线，如果要就添加一个透明的2d饼状图并调整角度使得labelLine和3d的饼状图对齐，并再次setOption
    option.series.push({
        name: '设备类型分布', //自己根据场景修改
        backgroundColor: 'transparent',
        type: 'pie',
        label: {
            opacity: 1,
            fontSize: 13,
            lineHeight: 20
        },
        startAngle: -40, // 起始角度，支持范围[0, 360]。
        clockwise: false, // 饼图的扇区是否是顺时针排布。上述这两项配置主要是为了对齐3d的样式
        radius: ['20%', '50%'],
        center: ['50%', '50%'],
        data: pieData,
        itemStyle: {
            opacity: 0  //这里必须是0，不然2d的图会覆盖在表面
        }
    })
    myPieChart.setOption(option);
}

function barshow(params) {
    $.ajax({
        url: URL.getRecent7DaysAlarm + params,
        method: 'POST',
        dataType: 'json',
        async: true, // 设置为异步请求
        success: function (data) {
            const paletteSemanticRed = 'l(90) 0:#FFD700 1:#DF8347';
            const brandColor = 'l(90) 0:#4DA7F5 1:#336FF3';
            const dataWithIndex = data.map((item, index) => ({
                ...item,
                index: index,
            }));
            document.getElementById('latestBar').innerHTML = '';
            const columnPlot = new Column('latestBar', {
                data: dataWithIndex,
                xField: 'name',
                yField: 'value',
                seriesField: 'value',
                label: {
                    content: (originData) => {
                        return originData.value;
                    },
                    style: {
                        fill: '#fff',
                        stroke: '#fff',
                        fillOpacity: 0
                    },
                    offset: 6,
                },
                title: {
                    text: '34555',
                    style: {
                        color: '#fff'
                    },
                },
                tooltip: {
                    formatter: (datum) => {
                        return {name: datum.name, value: datum.value};
                    },
                },
                maxColumnWidth: 14,
                color: ({value}) => {
                    if (value >= 10) {
                        return paletteSemanticRed;
                    }
                    return brandColor;
                },
                legend: false,
                xAxis: {
                    label: {
                        autoHide: true,
                        autoRotate: false,
                        style: {
                            fill: '#fff',
                        }
                    },
                },
                yAxis: {
                    label: {
                        style: {
                            fill: '#fff',
                        }
                    },
                },
            }).render();
        }
    });

    $.ajax({
        url: URL.getRecent7DaysAlarmSummary + params,
        method: 'POST',
        dataType: 'json',
        async: true, // 设置为异步请求
        success: function (data) {
            $(".processed").html(data.processed);
            $(".todayCount").html(data.todayCount);
            $(".total").html(data.total);
            $(".unprocessed").html(data.unprocessed);
        }
    });


}

function initMap(params) {
    localStorage.setItem('clickCode', params);
    //获取地图
    let jsonDataUrl = contextPath + "/page/adminSystem/index/bigScreen/navigation/two/json/" + params + ".json";
    $.getJSON(jsonDataUrl, function (geoJson) {
        echarts.registerMap(params, geoJson);
        // 渲染中间的地图
        $.ajax({
            url: URL.getNetworkGeoMap + params,
            method: 'POST',
            dataType: 'json',
            async: true, // 设置为异步请求
            success: function (data) {
                devicerun(data.geoCoordMap, data.dataList, data.moveLineList, params)
            }
        });
    });
}


function changeNewMap(geoCoordMap, data, lineToLf, area) {
    let map = new Map();
    for (let i = 0; i < lineToLf.length; i++) {
        let lineToLfElement = lineToLf[i];
        map.set(lineToLfElement.toName, lineToLfElement);
    }
    var convertData = function (data) {
        var res = [];
        let from = null;
        for (var i = 0; i < data.length; i++) {
            let name = data[i].name;
            let newVar = map.get(name);
            from = newVar;
            var geoCoord = geoCoordMap[name];
            if (geoCoord) {
                let assetsValue = newVar ? newVar['assets'] : [];
                res.push({
                    name: name,
                    value: geoCoord.concat(data[i].value),
                    status: data[i].status,
                    level: data[i].level,
                    id: data[i].id,
                    pid: data[i].pid,
                    ppid: data[i].ppid,
                    province: data[i].province,
                    assets: assetsValue
                });
            }
        }
        if (lineToLf != null && lineToLf.length > 0) {
            let lineToLfElement = lineToLf[0];
            res.push({
                name: lineToLfElement['formName'],
                value: lineToLfElement['coords'][0].concat(0),
                isStart: true,
            });
        }
        return res;
    };
    let convertProvinceData = function (data) {
        let resProvince = [];
        let from = null;
        for (let i = 0; i < data.length; i++) {
            let name = data[i].name;
            let geoCoord = geoCoordMap[name];
            let newVar = map.get(name);
            from = newVar;
            if (geoCoord && data[i]['province']) {
                if (newVar) {
                    let assetsValue = newVar ? newVar['assets'] : [];
                    geoCoord = newVar['coords'][0];
                    resProvince.push({
                        name: name,
                        value: geoCoord.concat(data[i].value),
                        status: data[i].status,
                        level: data[i].level,
                        id: data[i].id,
                        assets: assetsValue
                    });
                } else {
                    if (lineToLf != null && lineToLf.length > 0) {
                        let lineToLfElement = lineToLf[0];
                        geoCoord = lineToLfElement['coords'][0];
                        resProvince.push({
                            name: name,
                            value: geoCoord.concat(data[i].value),
                            status: data[i].status,
                            id: data[i].id,
                            level: data[i].level,
                            assets: []
                        });
                    } else {
                        resProvince.push({
                            name: name,
                            value: geoCoord.concat(data[i].value),
                            status: data[i].status,
                            id: data[i].id,
                            level: data[i].level,
                            assets: []
                        });
                    }

                }

            }
        }
        if (resProvince.length === 0) {
            if (from) {
                return [{
                    name: from['formName'],
                    value: from['coords'][0].concat(0),
                    status: from[status],
                    assets: []
                }]
            }
        }

        return resProvince;
    };

    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext('2d');
    canvas.width = 65;
    canvas.height = 65;
    //绘制颜色偏向
    var Grd = ctx.createLinearGradient(0, 100, 100, 0);
    Grd.addColorStop(0, "orange");
    Grd.addColorStop(1, "blue");
    ctx.fillStyle = Grd;
    ctx.fillRect(0, 0, 100, 100);

    let mapOption = {
        // 必须设置
        tooltip: {
            show: false
        },
        // 地图阴影配置
        geo: {
            map: area,
            // 这里必须定义，不然后面series里面不生效
            tooltip: {
                show: false
            },
            label: {
                show: false
            },
            zoom: 1.02,
            silent: true, // 不响应鼠标时间
            show: true,
            roam: false, // 地图缩放和平移
            aspectScale: 0.75, // scale 地图的长宽比
            shading: 'realistic',
            realisticMaterial: {
                roughness: 1,
                textureTiling: 1,
                detailTexture: ctx.canvas.toDataURL()
                // detailTexture: './img/city_bg.png'
            },
            select: {
                disabled: true
            },
            itemStyle: {
                borderColor: '#949480',
                borderWidth: 2,
                shadowColor: '#080B15',
                shadowBlur: 80,
            },
            emphasis: {
                disabled: true,
                areaColor: '#00F1FF'
            },
            // 地图区域的多边形 图形样式 阴影效果
            // z值小的图形会被z值大的图形覆盖
            top: '4%',
            left: 'center',
            z: 1
        },
        series: [
            // 地图配置
            {
                type: 'map',
                map: area,
                zoom: 1,
                tooltip: {
                    show: false
                },
                label: {
                    show: false, // 显示省份名称
                    color: '#fff',
                    align: 'center'
                },
                top: '4%',
                left: 'center',
                aspectScale: 0.75,
                roam: false, // 地图缩放和平移
                shading: 'realistic',
                realisticMaterial: {
                    roughness: 1,
                    textureTiling: 1,
                    detailTexture: ctx.canvas.toDataURL()
                },
                itemStyle: {
                    borderColor: '#B4EAFC', // 省分界线颜色  阴影效果的
                    borderWidth: 2,
                    areaColor: {
                        image: document.createElement("img").src = `${contextPath}/page/adminSystem/index/bigScreen/navigation/two/img/map.png`,
                        repeat: 'no-repeat'
                    },
                    opacity: 1
                },
                emphasis: { // 聚焦后颜色
                    disabled: false, // 开启高亮
                    label: {
                        align: 'center',
                        color: '#fff',
                        show: false,
                    },
                    itemStyle: {
                        color: '#ffffff',
                        areaColor: '#0a8bd8'// 阴影效果 鼠标移动上去的颜色
                    }
                },
                z: 2,
                data: convertData(data),
                tooltip: {
                    show: true,
                    backgroundColor: 'rgba(0,0,0,0)',
                    padding: 0,
                    borderWidth: 0,
                    extraCssText: 'box-shadow: 0 0 0 rgba(0, 0, 0, 0);', // 去除box-shadow阴影
                    formatter: function (params) {
                        let data = params['data'];
                        if (data) {
                            let assets = data['assets'];
                            if (assets && assets.length !== 0) {
                                let str = `<div style="background:#33465A"><div style="width:274px;height:191px;color:#fff;padding:32px 32px 32px 40px;box-sizing: border-box;background: url('${contextPath}/page/adminSystem/index/bigScreen/navigation/two/img/ball.png') no-repeat;background-size:cover;background-position: center;">
<div style="font-size:18px;color:#9DDE7F;border-bottom:1px solid #00B3FB">${data['name']}</div>`;
                                for (let i = 0; i < assets.length; i++) {
                                    if (i < 2) {
                                        let asset = assets[i];
                                        let snoUnicode = asset['snoUnicode'];
                                        let typeStr = "交换机";
                                        let switchRegex = /switch$/i; // 正则表达式，$表示结尾，i表示不区分大小写
                                        if (switchRegex.test(snoUnicode)) {
                                            typeStr = "交换机";
                                        } else {
                                            typeStr = "防火墙";
                                        }
                                        let connected = "异常";
                                        if (asset['connected']) {
                                            connected = "正常";
                                        }
                                        str += `<div>${typeStr}</div>
                                        <div>状态：${connected}</div>
                                        <div style="border-bottom:1px solid #00B3FB">ip：${asset['ip']}</div>`;
                                    }
                                }
                                str += `</div></div>`;
                                return str;
                            }

                        }
                        return '';


                    }
                },
            },
            {
                name: '省会',
                type: 'effectScatter',
                coordinateSystem: 'geo',
                // Geo 组件在 option 中的 index
                geoIndex: 0,
                zlevel: 2,
                showEffectOn: 'render',
                symbol: `image://${contextPath}/page/adminSystem/index/bigScreen/navigation/two/img/provinceCity.png`,
                rippleEffect: {
                    // scale: 3,
                    scale: 0,
                    brushType: 'stroke',
                },
                hoverAnimation: true,   //鼠标移上去显示数据
                label: {
                    normal: {
                        show: false,
                        position: 'right',
                        formatter: '{b}',
                    },
                    emphasis: {
                        show: false
                    }
                },
                symbolSize: function (val) {
                    return 120;
                },
                itemStyle: {
                    normal: {
                        color: '#2BEDE6',//#F4E925
                        shadowBlur: 10,
                        shadowColor: '#05C3F9'
                    }
                },
                viewControl: {			// 用于鼠标的旋转，缩放等视角控制。
                    projection: 'perspective', // 先设置为这个perspective
                    distance: 140,              //默认缩放比例
                },
                z: 5,
                data: convertProvinceData(data),
                tooltip: {
                    show: true,
                    backgroundColor: 'rgba(0,0,0,0)',
                    padding: 0,
                    borderWidth: 0,
                    extraCssText: 'box-shadow: 0 0 0 rgba(0, 0, 0, 0);', // 去除box-shadow阴影
                    formatter: function (params) {
                        let data = params['data'];
                        if (data) {
                            let assets = data['assets'];
                            if (assets && assets.length !== 0) {
                                let str = `<div style="background:#33465A"><div style="width:274px;height:191px;color:#fff;padding:32px 32px 32px 40px;box-sizing: border-box;background: url('${contextPath}/page/adminSystem/index/bigScreen/navigation/two/img/ball.png') no-repeat;background-size:cover;background-position: center;">
<div style="font-size:18px;color:#9DDE7F;border-bottom:1px solid #00B3FB">${data['name']}</div>`;
                                for (let i = 0; i < assets.length; i++) {
                                    if (i < 2) {
                                        let asset = assets[i];
                                        let snoUnicode = asset['snoUnicode'];
                                        let typeStr = "交换机";
                                        let switchRegex = /switch$/i; // 正则表达式，$表示结尾，i表示不区分大小写
                                        if (switchRegex.test(snoUnicode)) {
                                            typeStr = "交换机";
                                        } else {
                                            typeStr = "防火墙";
                                        }
                                        let connected = "异常";
                                        if (asset['connected']) {
                                            connected = "正常";
                                        }
                                        str += `<div>${typeStr}</div>
                                        <div>状态：${connected}</div>
                                        <div style="border-bottom:1px solid #00B3FB">ip：${asset['ip']}</div>`;
                                    }
                                }
                                str += `</div></div>`;
                                return str;
                            }

                        }
                        return '';


                    }
                },
            },
            // 点
            {
                type: 'effectScatter',
                coordinateSystem: 'geo',
                showEffectOn: 'render',
                // zlevel: 2, // zlevel用于 Canvas 分层 相同的绘制在同一个canvas上
                rippleEffect: {
                    number: 5, // 波纹数量
                    period: 4, // 动画周期 数值越大，波动越慢
                    scale: 3, // 动画中波纹的最大缩放比例
                    brushType: 'stroke' // 波纹的绘制方式 stroke fill
                },
                label: {
                    show: true,
                    position: 'right',
                    formatter: '{b}',
                    color: '#fff',
                    FontSize: '14px'
                },
                symbol: 'circle',
                symbolSize: 16,
                itemStyle: {
                    normal: {
                        color: function (params) {
                            return new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: params['data']['isStart'] ? '#9B1A25' : '#fff'
                            }, {
                                offset: 1,
                                color: params['data']['isStart'] ? '#9B1A25' : '#fff'
                            }], false)
                        },
                    }
                },
                data: convertData(data),
                // data: points,
                tooltip: {
                    show: true,
                    backgroundColor: 'rgba(0,0,0,0)',
                    padding: 0,
                    borderWidth: 0,
                    extraCssText: 'box-shadow: 0 0 0 rgba(0, 0, 0, 0);', // 去除box-shadow阴影
                    formatter: function (params) {
                        let data = params['data'];
                        if (data) {
                            let assets = data['assets'];
                            if (assets && assets.length !== 0) {
                                let str = `<div style="background:#33465A"><div style="width:274px;height:191px;color:#fff;padding:32px 32px 32px 40px;box-sizing: border-box;background: url('${contextPath}/page/adminSystem/index/bigScreen/navigation/two/img/ball.png') no-repeat;background-size:cover;background-position: center;">
<div style="font-size:18px;color:#9DDE7F;border-bottom:1px solid #00B3FB">${data['name']}</div>`;
                                for (let i = 0; i < assets.length; i++) {
                                    if (i < 2) {
                                        let asset = assets[i];
                                        let snoUnicode = asset['snoUnicode'];
                                        let typeStr = "交换机";
                                        let switchRegex = /switch$/i; // 正则表达式，$表示结尾，i表示不区分大小写
                                        if (switchRegex.test(snoUnicode)) {
                                            typeStr = "交换机";
                                        } else {
                                            typeStr = "防火墙";
                                        }
                                        let connected = "异常";
                                        if (asset['connected']) {
                                            connected = "正常";
                                        }
                                        str += `<div>${typeStr}</div>
                                        <div>状态：${connected}</div>
                                        <div style="border-bottom:1px solid #00B3FB">ip：${asset['ip']}</div>`;
                                    }
                                }
                                str += `</div></div>`;
                                return str;
                            }

                        }
                        return '';


                    }
                },
                z: 4
            },
            // 地图线的动画效果
            {
                type: 'lines',
                // zlevel: 1,
                effect: {
                    show: true,
                    period: 3, // 箭头指向速度，值越小速度越快
                    trailLength: 0.1, // 特效尾迹长度[0,1]值越大，尾迹越长重
                    symbol: 'arrow', // 箭头图标
                    symbolSize: 6 // 图标大小
                },
                lineStyle: {
                    // color: '#1DE9B6',
                    // 线条颜色
                    // color: '#0fff17',
                    color: function (params) {
                        return new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: params['data']['status'] == 1 ? '#13d90e' : (params['data']['status'] == 2 ? 'yellow' : (params['data']['status'] == 3 ? 'red' : ''))
                        }, {
                            offset: 1,
                            color: params['data']['status'] == 1 ? '#13d90e' : (params['data']['status'] == 2 ? 'yellow' : (params['data']['status'] == 3 ? 'red' : ''))
                        }], false)
                    },
                    width: 2, // 线条宽度
                    opacity: 0.8, // 尾迹线条透明度
                    curveness: 0.2 // 尾迹线条曲直度
                },
                data: lineToLf,
                z: 3
            }
        ]
    }
    return mapOption;
}

function devicerun(geoCoordMap, data, lineToLf, area) {
    // 基于准备好的dom，初始化echarts实例
    geoMapChart.clear();
    geoMapChart.dispose();
    geoMapChart = echarts.init(document.getElementById('deviceMap'));
    let mapOption = changeNewMap(geoCoordMap, data, lineToLf, area);
    // 绘制图表
    geoMapChart.setOption(mapOption, true);
    //点击地图事件
    geoMapChart.off('click');
    geoMapChart.on("dblclick", (params) => {
        let data = params.data;
        if (data && data.level) {
            let level = data.level;
            let id = data.id;
            let ppid = data.ppid;
            if (level === "2") {
                globalCode = ppid;
                initMap(ppid);
            } else if (level === "1" || level === "0") {
                globalCode = id;
                initMap(id);
            } else {
                globalCode = code;
                initMap(code);
            }
        } else {
            globalCode = code;
            initMap(code);
        }
    });
}

function getPie3D(pieData, internalDiameterRatio, distance, alpha, pieHeight, opacity = 1) {
    const series = []
    let sumValue = 0
    let startValue = 0
    let endValue = 0
    let legendData = []
    let legendBfb = []
    const k = 1 - internalDiameterRatio
    pieData.sort((a, b) => {
        return b.value - a.value
    })
    // 为每一个饼图数据，生成一个 series-surface 配置
    for (let i = 0; i < pieData.length; i++) {
        sumValue += pieData[i].value
        const seriesItem = {
            name:
                typeof pieData[i].name === 'undefined'
                    ? `series${i}`
                    : pieData[i].name,
            type: 'surface',
            parametric: true,
            wireframe: {
                show: false
            },
            pieData: pieData[i],
            pieStatus: {
                selected: false,
                hovered: false,
                k: k
            },
            center: ['10%', '50%']
        }
        if (typeof pieData[i].itemStyle !== 'undefined') {
            const itemStyle = {}
            itemStyle.color =
                typeof pieData[i].itemStyle.color !== 'undefined'
                    ? pieData[i].itemStyle.color
                    : opacity
            itemStyle.opacity =
                typeof pieData[i].itemStyle.opacity !== 'undefined'
                    ? pieData[i].itemStyle.opacity
                    : opacity
            seriesItem.itemStyle = itemStyle
        }
        series.push(seriesItem)
    }

    // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
    // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
    legendData = []
    legendBfb = []
    for (let i = 0; i < series.length; i++) {
        endValue = startValue + series[i].pieData.value
        series[i].pieData.startRatio = startValue / sumValue
        series[i].pieData.endRatio = endValue / sumValue
        series[i].parametricEquation = getParametricEquation(
            series[i].pieData.startRatio,
            series[i].pieData.endRatio,
            false,
            false,
            k,
            series[i].pieData.value
        )
        startValue = endValue
        const bfb = fomatFloat(series[i].pieData.value / sumValue, 4)
        legendData.push({
            name: series[i].name,
            value: bfb
        })
        legendBfb.push({
            name: series[i].name,
            value: bfb
        })
    }
    const boxHeight = getHeight3D(series, pieHeight) // 通过pieHeight设定3d饼/环的高度，单位是px
    // 准备待返回的配置项，把准备好的 legendData、series 传入。
    const option = {
        legend: {
            show: false,
            data: legendData,
            orient: 'vertical',
            left: 10,
            top: 10,
            itemGap: 10,
            textStyle: {
                color: '#A1E2FF'
            },
            icon: 'circle',
            formatter: function (param) {
                const item = legendBfb.filter(item => item.name === param)[0]
                const bfs = fomatFloat(item.value * 100, 2) + '%'
                return `${item.name}  ${bfs}`
            }
        },
        labelLine: {
            show: true,
            lineStyle: {
                color: '#fff'
            }
        },
        label: {
            show: true,
            position: 'outside',
            formatter: '{b} \n{c} {d}%'
        },
        tooltip: {
            backgroundColor: '#033b77',
            borderColor: '#21f2c4',
            textStyle: {
                color: '#fff',
                fontSize: 13
            },
            formatter: params => {
                if (
                    params.seriesName !== 'mouseoutSeries' &&
                    params.seriesName !== 'pie2d'
                ) {
                    const bfb = (
                        (option.series[params.seriesIndex].pieData.endRatio -
                            option.series[params.seriesIndex].pieData.startRatio) *
                        100
                    ).toFixed(2)
                    return (
                        `${params.seriesName}<br/>` +
                        `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>` +
                        `${bfb}%`
                    )
                }
            }
        },
        xAxis3D: {
            min: -1,
            max: 1
        },
        yAxis3D: {
            min: -1,
            max: 1
        },
        zAxis3D: {
            min: -1,
            max: 1
        },
        grid3D: {
            show: false,
            boxHeight: boxHeight, // 圆环的高度
            viewControl: {
                // 3d效果可以放大、旋转等，请自己去查看官方配置
                alpha, // 角度
                distance, // 调整视角到主体的距离，类似调整zoom
                rotateSensitivity: 0, // 设置为0无法旋转
                zoomSensitivity: 0, // 设置为0无法缩放
                panSensitivity: 0, // 设置为0无法平移
                autoRotate: false // 自动旋转
            }
        },
        series: series
    }
    return option
}

function getParametricEquation(startRatio, endRatio, isSelected, isHovered, k, h) {
    // 计算
    const midRatio = (startRatio + endRatio) / 2
    const startRadian = startRatio * Math.PI * 2
    const endRadian = endRatio * Math.PI * 2
    const midRadian = midRatio * Math.PI * 2
    // 如果只有一个扇形，则不实现选中效果。
    if (startRatio === 0 && endRatio === 1) {
        isSelected = false
    }
    // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
    k = typeof k !== 'undefined' ? k : 1 / 3
    // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
    const offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0
    const offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0
    // 计算高亮效果的放大比例（未高亮，则比例为 1）
    const hoverRate = isHovered ? 1.05 : 1
    // 返回曲面参数方程
    return {
        u: {
            min: -Math.PI,
            max: Math.PI * 3,
            step: Math.PI / 32
        },
        v: {
            min: 0,
            max: Math.PI * 2,
            step: Math.PI / 20
        },
        x: function (u, v) {
            if (u < startRadian) {
                return (
                    offsetX +
                    Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
                )
            }
            if (u > endRadian) {
                return (
                    offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
                )
            }
            return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate
        },
        y: function (u, v) {
            if (u < startRadian) {
                return (
                    offsetY +
                    Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
                )
            }
            if (u > endRadian) {
                return (
                    offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
                )
            }
            return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate
        },
        z: function (u, v) {
            if (u < -Math.PI * 0.5) {
                return Math.sin(u)
            }
            if (u > Math.PI * 2.5) {
                return Math.sin(u) * h * 0.1
            }
            return Math.sin(v) > 0 ? 1 * h * 0.1 : -1
        }
    }
}

function getHeight3D(series, height) {
    series.sort((a, b) => {
        return b.pieData.value - a.pieData.value
    })
    return (height * 25) / series[0].pieData.value
}

function fomatFloat(num, n) {
    let f = parseFloat(num)
    if (isNaN(f)) {
        return false
    }
    f = Math.round(num * Math.pow(10, n)) / Math.pow(10, n) // n 幂
    let s = f.toString()
    let rs = s.indexOf('.')
    // 判定如果是整数，增加小数点再补0
    if (rs < 0) {
        rs = s.length
        s += '.'
    }
    while (s.length <= rs + n) {
        s += '0'
    }
    return s
}

function getTime() {

    let times = new Date();
    const weekDays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const today = new Date();
    // 获取星期几
    const dayOfWeek = weekDays[today.getDay()];
    let date = times.getDate(), year = times.getFullYear(), month = times.getMonth(), hours = times.getHours(),
        min = times.getMinutes(), sec = times.getSeconds();
    let hss = isTwo(hours) + ':' + isTwo(min) + ':' + isTwo(sec);
    $('.hss').text(hss);
    $('.year').text(year);
    $('.monthdate').text(isTwo(month + 1) + '-' + isTwo(date));
    $('.week').text(dayOfWeek);
}

function isTwo(param) {
    return String(param).length >= 2 ? param : '0' + param
}

$('.jump').on('click', (e) => {
    $('.jump').css({background: '#0D1119', border: '1px solid #015B87'})
    $('.' + e.target.classList[1]).css({background: '#00A5F3', border: '1px solid #00A5F3'});
});


$(function () {
    let code = localStorage.getItem('defCode');
    init(code);
    getTime()
    getAllDc();
    setInterval(function () {
        let clickCode = localStorage.getItem('clickCode');
        init(clickCode);

    }, 20000);
    setInterval(function () {
        getTime()
    }, 1000)
})
